﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using Demo.Web.Filters;
using Demo.Web.Models;

using Demo.Web.UserService;


namespace Demo.Web.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class AccountController : Demo.Web.Controllers.BaseController
    {
        UserServiceClient client = new UserServiceClient();

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = client.GetUserDTOWithName(model.UserName);
                if (user != null)
                {
                    var password = FormsAuthentication.HashPasswordForStoringInConfigFile(model.Password, "MD5").ToUpper();
                    if (password == user.Password)
                    {
                        FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                        Session["User"] = user;
                        if (string.IsNullOrEmpty(returnUrl))
                            return RedirectToAction("Index", "Home");
                        else
                            return Redirect(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("", "提供的密码不正确。");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "提供的用户名不正确。");
                }
            }
            else
            {
                // 如果我们进行到这一步时某个地方出错，则重新显示表单
                ModelState.AddModelError("", "提供的用户名或密码不正确。");
            }
            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            Session["User"] = null;
            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        public ActionResult AjaxLogOff()
        {
            FormsAuthentication.SignOut();
            Session["User"] = null;
            return Content("True");
        }

        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // 尝试注册用户
                try
                {
                    var user = client.GetUserDTOWithName(model.UserName);
                    if (user == null)
                    {
                        model.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(model.Password, "MD5").ToUpper();
                        client.CreateUser(model.UserName, model.Password, 1);
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        ModelState.AddModelError("", "提供的用户名已经注册过！");
                    }  
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", e.StatusCode.ToString());
                }
            }
            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        [AllowAnonymous]
        public ActionResult NoAccess()
        {
            return View();
        }
    }
}
